package com.szy.controller;

import com.szy.entity.User;
import com.szy.repo.UserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.inject.Inject;

/**
 * Created by As on 2015/8/28.
 */
@Controller
@RequestMapping("/register")
public class RegisterController {

    private static final Logger log = LoggerFactory.getLogger(RegisterController.class);

    @Inject
    private UserRepository userRepository;

    @RequestMapping(method = RequestMethod.GET)
    public String register() {
        return "register";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String register(String name, String username, String password, String password2, Model model){
        if (userRepository.isUserExist(username)) {
            log.debug("用户名已被占用");
            model.addAttribute("message", "用户名"+username+"已被使用, 请重新注册!");
            return "register";
        } else if (!password.equals(password2)) {
            log.debug("两次输入的密码不同，请再次输入");
            model.addAttribute("message","两次密码不同, 请重新注册!");
            return "register";
        } else {
            User user = new User();
            user.setName(name);
            user.setUsername(username);
            user.setPassword(password);
            userRepository.saveAndFlush(user);
            log.debug("用户注册成功，跳转到登录页面");
            return "redirect:/login";
        }
    }
}